﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SQLite; 
using System.IO;
using System.Diagnostics;
using System.Net.NetworkInformation;//获取网口信息
using WPCAutomatic.DAL;//引用数据访问层

using SourceControl;
using SourceControl.Package;
using SourceControl.WSD;
using Wisdom.ProtocolLib;


namespace WPCAutomatic
{
    public partial class WPC : Form
    {

        // 添加一个字典来跟踪ComboBox的可见状态
        private Dictionary<string, bool> comboBoxVisibilityStates = new Dictionary<string, bool>();

        private bool isDataGridViewInitialized = false; // 标志变量确保只初始化一次

        // SQLite连接字符串 - 数据库文件放在项目文件夹中
        private readonly string ThresholdconnectionString = "Data Source=Threshold.db;Version=3;"; //门限校准值的连接

        private readonly string connectionSchemeString = "Data Source=Scheme.db;Version=3;";//方案参数--寄存器、寄存器值存储连接

        private readonly string connectionETableConst = "Data Source=ParametersConfiguration.db;Version=3;";//tabPage1常数值读取连接

        private readonly HFconst _hFconst; //DAL中的HFconst实例

        private readonly ThresholdScheme _thresholdScheme; //DAL中的门限实例


        private ETableConst _eTableConst;//DAL中的电表常数实例

        private readonly AChaneelsUp _achaneelsUp; // DAL中的升源参数(额定电压、额定电流)实例

        private Timer timer;
        public WPC()
        {
            InitializeComponent();

            dataGridView2.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            dataGridView2.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;

            // 初始化COM端口和波特率下拉框
            InitializeComPortComboBoxes();
            InitializeBaudRateComboBoxes();

            // 初始化可见性状态跟踪
            InitializeVisibilityTracking();

            // 加载保存的checkBoxList1选中状态
            LoadCheckedItems();

            // 根据checkBoxList1选中状态显示对应的ComboBox
            UpdateComboBoxVisibility();

            // 加载保存的COM端口和波特率设置
            LoadComPortSettings();

            InitializeDataGridViewColumns();

            _hFconst = new HFconst(connectionSchemeString);//通过构造函数注入DAL.HFconst实例

            _thresholdScheme = new ThresholdScheme(ThresholdconnectionString);//通过构造函数注入DAL.ThresholdScheme实例

            _eTableConst = new ETableConst(connectionETableConst);//通过构造函数注入DAL.ETableConst实例

            _achaneelsUp = new AChaneelsUp(connectionETableConst); // 初始化


            // 初始化时加载功率源网口信息
            LoadNetworkInterfaces();

            //初始化从数据库中加载电表常数信息
            LoadETableConst();

            // 订阅textBox1的文本变化事件 -----校准初始化中的HFCONST值变化后实时存储在数据库中
            textBox1.TextChanged += TextBox1_TextChanged;

            // 订阅textBox2和textBox3的文本变化事件
            textBox2.TextChanged += TextBox2_TextChanged;
            textBox3.TextChanged += TextBox3_TextChanged;


            // 订阅tabControl的选择变化事件 ---主要是为了校表门限初始化
            tabControl1.SelectedIndexChanged += tabControl1_SelectedIndexChanged;

            // 订阅comboBox103的选择变化事件 ----- 删除或显示对应的方案
            comboBox103.SelectedIndexChanged += comboBox103_SelectedIndexChanged;


            // 初始化计时器用于更新时间显示
            InitializeTimer();

            //打开界面自动最大化设置
            this.WindowState = FormWindowState.Maximized;

            // 启用自定义绘制---针对tabControl1选中分页标题头的明显点击效果
            tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;
            tabControl1.DrawItem += TabControl1_DrawItem;

            //绘制tabPage1分割线的颜色
            splitContainer1.SplitterWidth = 5; // 设置分割条宽度
            splitContainer1.Paint += splitContainer1_Paint; // 绑定绘制事件   

            // 绘制tabPage2分割线的颜色
            splitContainer2.SplitterWidth = 5; // 设置分割条宽度
            splitContainer2.Paint += splitContainer1_Paint; // 绑定绘制事件   

            // 加载保存TextBox1中的HFconst值
            LoadInitializationHFconstValue();

            LoadAchaneelUpValues(); // 新增的加载方法
        }


        private void InitializeDataGridViewColumns()
        {
            dataGridView2.Columns.Add("colProject", "项目\\表位");
            dataGridView2.Columns["colProject"].SortMode = DataGridViewColumnSortMode.NotSortable;
            dataGridView2.Rows.Add(10);
            dataGridView2.Rows[0].Cells[0].Value = "读取表位地址";//
            dataGridView2.Rows[1].Cells[0].Value = "进入工厂模式";//
            dataGridView2.Rows[2].Cells[0].Value = "1.0 100%UA 100%IA 校表初始化";
            dataGridView2.Rows[3].Cells[0].Value = "1.0 100%UA 100%IA 功率增益校准";
            dataGridView2.Rows[4].Cells[0].Value = "0.5L 100%UA 100%IA 相位校准";
            dataGridView2.Rows[5].Cells[0].Value = "1.0 100%UA 5%IA 有功功率偏置校准";
            dataGridView2.Rows[6].Cells[0].Value = "1.0 100%UA 0%IA 日计时校准";
            dataGridView2.Rows[7].Cells[0].Value = "1.0 100%UA 0%IA 电流偏置校准";
            dataGridView2.Rows[8].Cells[0].Value = "1.0 100%UA 100%IA 零线系数校准";
            dataGridView2.Rows[9].Cells[0].Value = "退出工厂模式";
        }


        private void UpdateDataGridViewHeaders()
        {
            while (dataGridView2.Columns.Count > 1)
            {
                dataGridView2.Columns.RemoveAt(1);
            }
            for (int i = 5; i <= 52; i++)
            {
                var comboBox = Controls.Find($"comboBox{i}", true).FirstOrDefault() as ComboBox;
                var baudComboBox = Controls.Find($"comboBox{i + 50}", true).FirstOrDefault() as ComboBox;
                if (comboBox != null && baudComboBox != null &&
                    comboBox.Visible && comboBox.SelectedItem != null &&
                    baudComboBox.Visible && baudComboBox.SelectedItem != null)
                {
                    int positionNumber = i - 4;
                    var newCol = new DataGridViewTextBoxColumn
                    {
                        HeaderText = $"第{positionNumber}表位",
                        Name = $"colPos{positionNumber}",
                        SortMode = DataGridViewColumnSortMode.NotSortable
                    };
                    dataGridView2.Columns.Add(newCol);
                }
            }
            dataGridView2.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            dataGridView2.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells);
            foreach (DataGridViewColumn column in dataGridView2.Columns)
            {
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            }
        }




        private void InitializeVisibilityTracking()
        {
            // 初始化所有ComboBox的可见性状态跟踪（不包括新增的4个固定显示的ComboBox）
            for (int i = 5; i <= 52; i++)
            {
                string key = $"comboBox{i}";
                comboBoxVisibilityStates[key] = false;
            }
            for (int i = 55; i <= 102; i++)
            {
                string key = $"comboBox{i}";
                comboBoxVisibilityStates[key] = false;
            }
        }



        private void InitializeComPortComboBoxes()
        {
            // 获取系统中所有可用的串口
            string[] availablePorts = System.IO.Ports.SerialPort.GetPortNames();

            // 初始化新增的固定显示的COM端口下拉框（comboBox3和comboBox4）
            InitializeFixedComPortComboBox("comboBox3", availablePorts);
            InitializeFixedComPortComboBox("comboBox4", availablePorts);

            // 初始化其他COM端口下拉框选项
            for (int i = 5; i <= 52; i++)
            {
                ComboBox comboBox = Controls.Find($"comboBox{i}", true).FirstOrDefault() as ComboBox;
                if (comboBox != null)
                {
                    comboBox.Items.Clear();
                    foreach (string port in availablePorts)
                    {
                        comboBox.Items.Add(port);
                    }
                    comboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
                }
            }
        }


        private void InitializeFixedComPortComboBox(string comboBoxName, string[] availablePorts)
        {
            ComboBox comboBox = Controls.Find(comboBoxName, true).FirstOrDefault() as ComboBox;
            if (comboBox != null)
            {
                comboBox.Items.Clear();
                foreach (string port in availablePorts)
                {
                    comboBox.Items.Add(port);
                }
                comboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
            }
        }


        private void InitializeBaudRateComboBoxes()
        {
            // 初始化新增的固定显示的波特率下拉框（comboBox53和comboBox54）
            InitializeFixedBaudRateComboBox("comboBox53");
            InitializeFixedBaudRateComboBox("comboBox54");
            // 初始化其他波特率下拉框选项
            int[] baudRates = { 9600, 19200, 38400 };
            for (int i = 55; i <= 102; i++)
            {
                ComboBox comboBox = Controls.Find($"comboBox{i}", true).FirstOrDefault() as ComboBox;
                if (comboBox != null)
                {
                    comboBox.Items.Clear();
                    foreach (int rate in baudRates)
                    {
                        comboBox.Items.Add(rate.ToString());
                    }
                    comboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
                }
            }
        }


        private void InitializeFixedBaudRateComboBox(string comboBoxName)
        {
            int[] baudRates = { 9600, 19200, 38400 };
            ComboBox comboBox = Controls.Find(comboBoxName, true).FirstOrDefault() as ComboBox;
            if (comboBox != null)
            {
                comboBox.Items.Clear();
                foreach (int rate in baudRates)
                {
                    comboBox.Items.Add(rate.ToString());
                }
                comboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
            }
        }



        private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 保存COM端口和波特率设置
            SaveComPortSettings();
            UpdateDataGridViewHeaders();
        }

        private void LoadComPortSettings()
        {
            // 加载保存的COM端口设置
            if (Properties.Settings.Default.ComPortSettings != null)
            {
                var savedSettings = Properties.Settings.Default.ComPortSettings.Cast<string>().ToList();
                // 先加载新增的4个固定ComboBox的设置（放在最前面）
                LoadFixedComboBoxSettings(savedSettings);
                // 然后加载其他ComboBox的设置
                for (int i = 0; i < 48; i++)
                {
                    // 加载COM端口设置 (comboBox5~comboBox52)
                    if (i + 4 < savedSettings.Count && !string.IsNullOrEmpty(savedSettings[i + 4]))
                    {
                        ComboBox comboBox = Controls.Find($"comboBox{i + 5}", true).FirstOrDefault() as ComboBox;
                        if (comboBox != null)
                        {
                            int index = comboBox.Items.IndexOf(savedSettings[i + 4]);
                            if (index >= 0)
                            {
                                comboBox.SelectedIndex = index;
                            }
                        }
                    }
                    // 加载波特率设置 (comboBox55~comboBox102)
                    if (i + 52 < savedSettings.Count && !string.IsNullOrEmpty(savedSettings[i + 52]))
                    {
                        ComboBox comboBox = Controls.Find($"comboBox{i + 55}", true).FirstOrDefault() as ComboBox;
                        if (comboBox != null)
                        {
                            int index = comboBox.Items.IndexOf(savedSettings[i + 52]);
                            if (index >= 0)
                            {
                                comboBox.SelectedIndex = index;
                            }
                        }
                    }
                }
            }
        }

        private void LoadFixedComboBoxSettings(List<string> savedSettings)
        {
            // 加载comboBox3的设置（索引0）
            if (savedSettings.Count > 0 && !string.IsNullOrEmpty(savedSettings[0]))
            {
                ComboBox comboBox = Controls.Find("comboBox3", true).FirstOrDefault() as ComboBox;
                if (comboBox != null)
                {
                    int index = comboBox.Items.IndexOf(savedSettings[0]);
                    if (index >= 0)
                    {
                        comboBox.SelectedIndex = index;
                    }
                }
            }
            // 加载comboBox4的设置（索引1）
            if (savedSettings.Count > 1 && !string.IsNullOrEmpty(savedSettings[1]))
            {
                ComboBox comboBox = Controls.Find("comboBox4", true).FirstOrDefault() as ComboBox;
                if (comboBox != null)
                {
                    int index = comboBox.Items.IndexOf(savedSettings[1]);
                    if (index >= 0)
                    {
                        comboBox.SelectedIndex = index;
                    }
                }
            }
            // 加载comboBox53的设置（索引2）
            if (savedSettings.Count > 2 && !string.IsNullOrEmpty(savedSettings[2]))
            {
                ComboBox comboBox = Controls.Find("comboBox53", true).FirstOrDefault() as ComboBox;
                if (comboBox != null)
                {
                    int index = comboBox.Items.IndexOf(savedSettings[2]);
                    if (index >= 0)
                    {
                        comboBox.SelectedIndex = index;
                    }
                }
            }
            // 加载comboBox54的设置（索引3）
            if (savedSettings.Count > 3 && !string.IsNullOrEmpty(savedSettings[3]))
            {
                ComboBox comboBox = Controls.Find("comboBox54", true).FirstOrDefault() as ComboBox;
                if (comboBox != null)
                {
                    int index = comboBox.Items.IndexOf(savedSettings[3]);
                    if (index >= 0)
                    {
                        comboBox.SelectedIndex = index;
                    }
                }
            }
        }

        private void SaveComPortSettings()
        {
            // 创建一个新的StringCollection来存储COM端口和波特率设置
            System.Collections.Specialized.StringCollection comPortSettings =
                new System.Collections.Specialized.StringCollection();
            // 先保存新增的4个固定ComboBox的设置（放在最前面）
            SaveFixedComboBoxSettings(comPortSettings);
            // 保存COM端口设置 (comboBox5~comboBox52)
            for (int i = 5; i <= 52; i++)
            {
                ComboBox comboBox = Controls.Find($"comboBox{i}", true).FirstOrDefault() as ComboBox;
                if (comboBox != null && comboBox.SelectedItem != null)
                {
                    comPortSettings.Add(comboBox.SelectedItem.ToString());
                }
                else
                {
                    comPortSettings.Add(string.Empty);
                }
            }
            // 保存波特率设置 (comboBox55~comboBox102)
            for (int i = 55; i <= 102; i++)
            {
                ComboBox comboBox = Controls.Find($"comboBox{i}", true).FirstOrDefault() as ComboBox;
                if (comboBox != null && comboBox.SelectedItem != null)
                {
                    comPortSettings.Add(comboBox.SelectedItem.ToString());
                }
                else
                {
                    comPortSettings.Add(string.Empty);
                }
            }
            // 保存到Settings
            Properties.Settings.Default.ComPortSettings = comPortSettings;
            Properties.Settings.Default.Save();
        }

        private void SaveFixedComboBoxSettings(System.Collections.Specialized.StringCollection comPortSettings)
        {
            // 保存comboBox3的设置
            ComboBox comboBox3 = Controls.Find("comboBox3", true).FirstOrDefault() as ComboBox;
            if (comboBox3 != null && comboBox3.SelectedItem != null)
            {
                comPortSettings.Add(comboBox3.SelectedItem.ToString());
            }
            else
            {
                comPortSettings.Add(string.Empty);
            }
            // 保存comboBox4的设置
            ComboBox comboBox4 = Controls.Find("comboBox4", true).FirstOrDefault() as ComboBox;
            if (comboBox4 != null && comboBox4.SelectedItem != null)
            {
                comPortSettings.Add(comboBox4.SelectedItem.ToString());
            }
            else
            {
                comPortSettings.Add(string.Empty);
            }
            // 保存comboBox53的设置
            ComboBox comboBox53 = Controls.Find("comboBox53", true).FirstOrDefault() as ComboBox;
            if (comboBox53 != null && comboBox53.SelectedItem != null)
            {
                comPortSettings.Add(comboBox53.SelectedItem.ToString());
            }
            else
            {
                comPortSettings.Add(string.Empty);
            }
            // 保存comboBox54的设置
            ComboBox comboBox54 = Controls.Find("comboBox54", true).FirstOrDefault() as ComboBox;
            if (comboBox54 != null && comboBox54.SelectedItem != null)
            {
                comPortSettings.Add(comboBox54.SelectedItem.ToString());
            }
            else
            {
                comPortSettings.Add(string.Empty);
            }
        }


        // 加载保存的选中状态
        private void LoadCheckedItems()
        {
            // 检查是否有保存的选中项
            if (Properties.Settings.Default.CheckedItems != null)
            {
                // 将保存的选中项转换为列表
                var savedItems = Properties.Settings.Default.CheckedItems.Cast<string>().ToList();
                // 遍历checkedListBox1中的所有项
                for (int i = 0; i < checkedListBox1.Items.Count; i++)
                {
                    // 如果该项在保存的列表中，则选中它
                    if (savedItems.Contains(checkedListBox1.Items[i].ToString()))
                    {
                        checkedListBox1.SetItemChecked(i, true);
                    }
                }
            }
        }

        private void UpdateComboBoxVisibility()
        {
            // 先检查并处理从显示变为隐藏的ComboBox
            CheckAndClearHiddenComboBoxes();

            // 先隐藏所有ComboBox
            ToggleComboBoxes(false);
            // 遍历所有选中的项，显示对应的ComboBox
            foreach (var item in checkedListBox1.CheckedItems)
            {
                // 获取选中项的索引（0-47）
                int index = checkedListBox1.Items.IndexOf(item);
                // 显示comboBox5~comboBox52中对应的项
                int comboIndex = index + 5; // 因为第1项(索引0)对应comboBox5
                Control[] controls = this.Controls.Find($"comboBox{comboIndex}", true);
                if (controls.Length > 0 && controls[0] is ComboBox comboBox)
                {
                    comboBox.Visible = true;
                    comboBoxVisibilityStates[$"comboBox{comboIndex}"] = true;
                }

                // 显示comboBox55~comboBox102中对应的项
                int comboIndex2 = index + 55; // 因为第1项(索引0)对应comboBox55
                Control[] controls2 = this.Controls.Find($"comboBox{comboIndex2}", true);
                if (controls2.Length > 0 && controls2[0] is ComboBox comboBox2)
                {
                    comboBox2.Visible = true;
                    comboBoxVisibilityStates[$"comboBox{comboIndex2}"] = true;
                }
            }
        }

        private void CheckAndClearHiddenComboBoxes()
        {
            // 检查所有ComboBox的可见性状态变化
            for (int i = 5; i <= 52; i++)
            {
                string key = $"comboBox{i}";
                ComboBox comboBox = Controls.Find(key, true).FirstOrDefault() as ComboBox;

                if (comboBox != null)
                {
                    // 如果之前是可见的，现在要隐藏
                    if (comboBoxVisibilityStates[key] && !comboBox.Visible)
                    {
                        // 清空选择
                        comboBox.SelectedIndex = -1;
                        // 更新保存的设置
                        SaveComPortSettings();
                    }
                    // 更新状态
                    comboBoxVisibilityStates[key] = comboBox.Visible;
                }
            }

            for (int i = 55; i <= 102; i++)
            {
                string key = $"comboBox{i}";
                ComboBox comboBox = Controls.Find(key, true).FirstOrDefault() as ComboBox;

                if (comboBox != null)
                {
                    // 如果之前是可见的，现在要隐藏
                    if (comboBoxVisibilityStates[key] && !comboBox.Visible)
                    {
                        // 清空选择
                        comboBox.SelectedIndex = -1;
                        // 更新保存的设置
                        SaveComPortSettings();
                    }
                    // 更新状态
                    comboBoxVisibilityStates[key] = comboBox.Visible;
                }
            }
        }




        // 保存选中状态到Settings
        private void SaveCheckedItems()
        {
            // 创建一个新的StringCollection来存储选中的项
            System.Collections.Specialized.StringCollection checkedItems =
                new System.Collections.Specialized.StringCollection();
            // 遍历checkedListBox1中的所有选中项
            foreach (var item in checkedListBox1.CheckedItems)
            {
                checkedItems.Add(item.ToString());
            }
            // 保存到Settings
            Properties.Settings.Default.CheckedItems = checkedItems;
            Properties.Settings.Default.Save();
        }
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            SaveCheckedItems();
            SaveComPortSettings();
        }
        private void ToggleComboBoxes(bool visible)
        {
            // 显示或隐藏comboBox5~comboBox52
            for (int i = 5; i <= 52; i++)
            {
                Control[] controls = this.Controls.Find($"comboBox{i}", true);
                if (controls.Length > 0 && controls[0] is ComboBox comboBox)
                {
                    // 记录状态变化
                    if (comboBox.Visible && !visible)
                    {
                        comboBoxVisibilityStates[$"comboBox{i}"] = false;
                    }
                    comboBox.Visible = visible;
                }
            }
            // 显示或隐藏comboBox55~comboBox102
            for (int i = 55; i <= 102; i++)
            {
                Control[] controls = this.Controls.Find($"comboBox{i}", true);
                if (controls.Length > 0 && controls[0] is ComboBox comboBox)
                {
                    // 记录状态变化
                    if (comboBox.Visible && !visible)
                    {
                        comboBoxVisibilityStates[$"comboBox{i}"] = false;
                    }
                    comboBox.Visible = visible;
                }
            }
        }
        //全选
        private void button2_Click(object sender, EventArgs e)
        {
            // 全选checkedListBox1中的所有项
            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                checkedListBox1.SetItemChecked(i, true);
            }
            // 显示所有ComboBox
            ToggleComboBoxes(true);

            UpdateDataGridViewHeaders();
        }
        //全清
        private void button3_Click(object sender, EventArgs e)
        {
            // 取消全选checkedListBox1中的所有项
            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                checkedListBox1.SetItemChecked(i, false);
            }
            // 隐藏所有ComboBox
            ToggleComboBoxes(false);

            // 清空所有ComboBox的选择
            ClearAllComboBoxSelections();

            UpdateDataGridViewHeaders();
        }

        private void ClearAllComboBoxSelections()
        {
            // 清空comboBox5~comboBox52的选择
            for (int i = 5; i <= 52; i++)
            {
                ComboBox comboBox = Controls.Find($"comboBox{i}", true).FirstOrDefault() as ComboBox;
                if (comboBox != null)
                {
                    comboBox.SelectedIndex = -1;
                }
            }

            // 清空comboBox55~comboBox102的选择
            for (int i = 55; i <= 102; i++)
            {
                ComboBox comboBox = Controls.Find($"comboBox{i}", true).FirstOrDefault() as ComboBox;
                if (comboBox != null)
                {
                    comboBox.SelectedIndex = -1;
                }
            }

            // 保存设置
            SaveComPortSettings();
        }


        //部分选择
        private void button4_Click(object sender, EventArgs e)
        {
            // 获取输入的范围
            int start, end;
            if (!int.TryParse(textBox4.Text, out start) || !int.TryParse(textBox5.Text, out end))
            {
                MessageBox.Show("请输入有效的数字范围");
                return;
            }
            // 验证范围是否有效
            if (start < 1 || end > 48 || start > end)
            {
                MessageBox.Show("请输入1-48之间的有效范围");
                return;
            }
            // 先取消所有选择
            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                checkedListBox1.SetItemChecked(i, false);
            }
            // 选择指定范围的项
            for (int i = start - 1; i < end; i++)
            {
                checkedListBox1.SetItemChecked(i, true);
            }
            // 更新ComboBox的可见性
            UpdateComboBoxVisibility();

            UpdateDataGridViewHeaders();
        }


        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            UpdateDataGridViewHeaders();
        }


        // 加载HFCONST初始化值
        private void LoadInitializationHFconstValue()
        {
            try
            {
                var value = _hFconst.GetInitializationHFconstValue();
                if (!string.IsNullOrEmpty(value))
                {
                    textBox1.Text = value;
                }
            }
            catch (Exception ex)
            {
                AppendThresholdInfo($"加载HFConst初始化值时出错: {ex.Message}");
            }
        }

        // 处理textBox1文本变化
        private void TextBox1_TextChanged(object sender, EventArgs e)
        {
            // 验证输入是否为有效的十六进制数
            string input = textBox1.Text.Trim();
            if (!string.IsNullOrEmpty(input))
            {
                // 简单的十六进制验证
                if (System.Text.RegularExpressions.Regex.IsMatch(input, @"^[0-9A-Fa-f]+$"))
                {
                    try
                    {
                        _hFconst.SaveInitializationHFconstValue(input);
                    }
                    catch (Exception ex)
                    {
                        AppendThresholdInfo($"保存HFconst初始化值时出错: {ex.Message}");
                    }
                }
                else
                {
                    MessageBox.Show("请输入有效的16进制数");
                }
            }
            else
            {
                // 输入为空时也保存
                try
                {
                    _hFconst.SaveInitializationHFconstValue("");
                }
                catch (Exception ex)
                {
                    AppendThresholdInfo($"保存HFcons初始化值时出错: {ex.Message}");
                }
            }
        }

        //加载AchaneelUp类中的A通道的额定电流和额定电压
        private void LoadAchaneelUpValues()
        {
            try
            {
                var (voltage, current) = _achaneelsUp.GetAchaneelUpValues();
                textBox2.Text = voltage;
                textBox3.Text = current;
            }
            catch (Exception ex)
            {
                AppendThresholdInfo($"加载额定电压/电流值时出错: {ex.Message}");
            }
        }
        // 处理textBox2文本变化
        private void TextBox2_TextChanged(object sender, EventArgs e)
        {
            string input = textBox2.Text.Trim();
            if (!string.IsNullOrEmpty(input))
            {
                // 验证是否为数字（整数或小数）
                if (decimal.TryParse(input, out _))
                {
                    try
                    {
                        _achaneelsUp.SaveAchaneelUpValues(input, textBox3.Text.Trim());
                    }
                    catch (Exception ex)
                    {
                        AppendThresholdInfo($"保存额定电压值时出错: {ex.Message}");
                    }
                }
                else
                {
                    MessageBox.Show("请输入有效的数字（整数或小数）");
                }
            }
            else
            {
                // 输入为空时也保存
                try
                {
                    _achaneelsUp.SaveAchaneelUpValues("", textBox3.Text.Trim());
                }
                catch (Exception ex)
                {
                    AppendThresholdInfo($"保存额定电压值时出错: {ex.Message}");
                }
            }
        }
        // 处理textBox3文本变化
        private void TextBox3_TextChanged(object sender, EventArgs e)
        {
            string input = textBox3.Text.Trim();
            if (!string.IsNullOrEmpty(input))
            {
                // 验证是否为数字（整数或小数）
                if (decimal.TryParse(input, out _))
                {
                    try
                    {
                        _achaneelsUp.SaveAchaneelUpValues(textBox2.Text.Trim(), input);
                    }
                    catch (Exception ex)
                    {
                        AppendThresholdInfo($"保存额定电流值时出错: {ex.Message}");
                    }
                }
                else
                {
                    MessageBox.Show("请输入有效的数字（整数或小数）");
                }
            }
            else
            {
                // 输入为空时也保存
                try
                {
                    _achaneelsUp.SaveAchaneelUpValues(textBox2.Text.Trim(), "");
                }
                catch (Exception ex)
                {
                    AppendThresholdInfo($"保存额定电流值时出错: {ex.Message}");
                }
            }
        }



        private void InitializeTimer()
        {
            timer = new Timer();
            timer.Interval = 1000; // 1秒更新一次
            timer.Tick += (s, e) => {
                toolStripStatusLabel1.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            };
            timer.Start();

            // 初始显示时间
            toolStripStatusLabel1.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        // 在richTextBox1中追加调试信息
        private void AppendThresholdInfo(string message)
        {
            if (richTextBox1.InvokeRequired)
            {
                richTextBox1.Invoke(new Action<string>(AppendThresholdInfo), message);
            }
            else
            {
                richTextBox1.AppendText($"[{DateTime.Now:HH:mm:ss}] {message}\n");
                richTextBox1.ScrollToCaret(); // 自动滚动到底部
            }
        }
        
        private void tabPage1_Click(object sender, EventArgs e)
        {
            
        }

        private void LoadETableConst()
        {
            LoadMeterConstants();
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 检查是否切换到tabPages3且尚未初始化
            if (tabControl1.SelectedTab == tabPage3 && !isDataGridViewInitialized)
            {
                InitializeDataGridView();
                isDataGridViewInitialized = true;
            }
        }

        private void LoadMeterConstants()
        {
            try
            {
                // 获取所有电表常数
                var constants = _eTableConst.GetAllMeterConstants();

                // 绑定到comboBox2
                comboBox2.DataSource = constants;

                // 获取上次保存的索引并设置当前选择
                int lastIndex = _eTableConst.GetLastSelectedIndex();
                if (lastIndex >= 0 && lastIndex < comboBox2.Items.Count)
                {
                    comboBox2.SelectedIndex = lastIndex;
                }

                // 订阅SelectedIndexChanged事件
                comboBox2.SelectedIndexChanged += ComboBox2_SelectedIndexChanged;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载电表常数失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }





        private void LoadNetworkInterfaces()
        {
            if (this.comboBox1.Items.Count == 0)
            {
                foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
                {
                    string a123 = nic.Description;
                    this.comboBox1.Items.Add(a123);
                }

                if (this.comboBox1.Items.Count > 0)
                {
                    this.comboBox1.SelectedIndex = 0;
                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }



        private void InitializeDataGridView()
        {
            // 设置dataGridView1的基本属性
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.AllowUserToDeleteRows = false;
            dataGridView1.RowHeadersVisible = false;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            // 添加列
            dataGridView1.Columns.Add("Column1", "校准对象");
            dataGridView1.Columns.Add("Column2", "误差上限");
            dataGridView1.Columns.Add("Column3", "误差下限");
            dataGridView1.Columns.Add("Column4", "单位");

            // 禁用所有列的排序功能
            foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            // 添加行数据
            string[] rowData = {
        "校表初始化",
        "功率增益校准",
        "相位校准",
        "电流偏置校准",
        "日计时校准",
        "零线校准"
    };

            // 设置第一列（校准对象）为只读
            dataGridView1.Columns[0].ReadOnly = true;

            foreach (var item in rowData)
            {
                int rowIndex = dataGridView1.Rows.Add(item, "", "", "");

                // 设置第一列（校准对象）的单元格为只读
                dataGridView1.Rows[rowIndex].Cells[0].ReadOnly = true;
            }

            // 自动调整行高和字体大小
            dataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells);

            // 设置合适的字体大小
            int fontSize = CalculateOptimalFontSize(dataGridView1);
            dataGridView1.DefaultCellStyle.Font = new Font("Microsoft YaHei", fontSize);
            dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Microsoft YaHei", fontSize);
        }

        // 计算最佳字体大小的方法
        private int CalculateOptimalFontSize(DataGridView dgv)
        {
            int baseSize = 9; // 基础字体大小
            int maxSize = 14; // 最大字体大小

            // 获取第一行的高度
            if (dgv.Rows.Count > 0)
            {
                int rowHeight = dgv.Rows[0].Height;

                // 根据行高计算字体大小
                int calculatedSize = (int)(rowHeight * 0.4);

                // 确保在合理范围内
                return Math.Min(Math.Max(baseSize, calculatedSize), maxSize);
            }

            return baseSize;
        }

        // 检查DataGridView中是否有空单元格
        private bool HasEmptyCells()
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                // 跳过第一列（校准对象），因为它是只读的
                for (int i = 1; i < row.Cells.Count; i++)
                {
                    if (string.IsNullOrWhiteSpace(row.Cells[i].Value?.ToString()))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        private void button6_Click_1(object sender, EventArgs e)
        {
            string schemeName = comboBox103.Text.Trim();
            if (string.IsNullOrWhiteSpace(schemeName))
            {
                MessageBox.Show("请输入方案名称！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (HasEmptyCells())
            {
                MessageBox.Show("字段信息不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (comboBox103.Items.Contains(schemeName))
            {
                MessageBox.Show("该方案名称已存在，请使用其他名称！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            try
            {
                var dataList = GetDataFromDataGridView();
                _thresholdScheme.SaveScheme(schemeName, dataList);

                comboBox103.Items.Add(schemeName);
                comboBox103.SelectedItem = schemeName;
                MessageBox.Show("创建校准门限方案成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存到数据库失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private List<ThresholdData> GetDataFromDataGridView()
        {
            var dataList = new List<ThresholdData>();
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.IsNewRow) continue;
                dataList.Add(new ThresholdData
                {
                    CalibrationObject = row.Cells["Column1"].Value?.ToString() ?? "",
                    UpperLimit = row.Cells["Column2"].Value?.ToString() ?? "",
                    LowerLimit = row.Cells["Column3"].Value?.ToString() ?? "",
                    Unit = row.Cells["Column4"].Value?.ToString() ?? ""
                });
            }
            return dataList;
        }

        private void TabControl1_DrawItem(object sender, DrawItemEventArgs e)
        {
            TabControl tc = sender as TabControl;
            TabPage tab = tc.TabPages[e.Index];
            Rectangle rect = tc.GetTabRect(e.Index);

            // 判断是否是选中的标签
            bool isSelected = (e.State & DrawItemState.Selected) == DrawItemState.Selected;
            // 设置不同状态的样式
            using (Brush backBrush = new SolidBrush(isSelected ? Color.Yellow : SystemColors.Control))
            using (Brush textBrush = new SolidBrush(isSelected ? Color.Red : SystemColors.ControlText))
            {
                // 绘制背景
                e.Graphics.FillRectangle(backBrush, e.Bounds);
                // 绘制图片（关键修改点）
                if (tc.ImageList != null && tab.ImageIndex >= 0)
                {
                    Image img = tc.ImageList.Images[tab.ImageIndex];
                    // 图片位置（距左侧3像素）
                    Rectangle imageRect = new Rectangle(
                        rect.X + 3,
                        rect.Y + (rect.Height - img.Height) / 2,
                        img.Width,
                        img.Height
                    );
                    e.Graphics.DrawImage(img, imageRect);

                    // 调整文字位置（图片右侧留出5像素间隔）
                    rect.X += img.Width + 8;
                    rect.Width -= img.Width + 8;
                }
                // 绘制文本
                StringFormat sf = new StringFormat
                {
                    Alignment = StringAlignment.Near,  // 左对齐
                    LineAlignment = StringAlignment.Center
                };
                e.Graphics.DrawString(tab.Text, e.Font, textBrush, rect, sf);
            }
            // 绘制边框（可选）
            if (isSelected)
            {
                using (Pen pen = new Pen(Color.Blue, 2))
                {
                    e.Graphics.DrawRectangle(pen, e.Bounds);
                }
            }
        }

        private void splitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
        {

        }

        private void splitContainer1_Paint(object sender, PaintEventArgs e)
        {
            var splitter = sender as SplitContainer;
            using (var brush = new SolidBrush(Color.SteelBlue)) // 设置任意颜色
            {
                e.Graphics.FillRectangle(brush, splitter.SplitterRectangle);
            }
        }

        private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void WPC_Load(object sender, EventArgs e)
        {
           
        }

        private void comboBox72_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                comboBox103.Items.Clear();

                var tableNames = _thresholdScheme.GetAllTableNames();
                foreach (var tableName in tableNames)
                {
                    comboBox103.Items.Add(tableName);
                    AppendThresholdInfo($"发现表: {tableName}");
                }
                AppendThresholdInfo($"共找到 {comboBox103.Items.Count} 个表");
                if (comboBox103.Items.Count > 0)
                {
                    comboBox103.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                AppendThresholdInfo($"获取表名失败: {ex.Message}");
                MessageBox.Show($"获取表名失败: {ex.Message}", "错误",
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ComboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 保存用户选择的索引
            if (comboBox2.SelectedIndex >= 0)
            {
                _eTableConst.SaveSelectedIndex(comboBox2.SelectedIndex);
            }
        }

        private void comboBox103_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox103.SelectedIndex == -1) return;
            string selectedTable = comboBox103.SelectedItem.ToString();
            LoadDataFromDatabase(selectedTable);
        }

        private void LoadDataFromDatabase(string tableName)
        {
            try
            {
                if (!isDataGridViewInitialized)
                {
                    InitializeDataGridView();
                    isDataGridViewInitialized = true;
                }
                dataGridView1.Rows.Clear();

                var dataList = _thresholdScheme.LoadDataFromTable(tableName);
                AppendThresholdInfo($"开始从表 {tableName} 加载数据...");
                foreach (var data in dataList)
                {
                    int rowIndex = dataGridView1.Rows.Add();
                    dataGridView1.Rows[rowIndex].Cells["Column1"].Value = data.CalibrationObject;
                    dataGridView1.Rows[rowIndex].Cells["Column2"].Value = data.UpperLimit;
                    dataGridView1.Rows[rowIndex].Cells["Column3"].Value = data.LowerLimit;
                    dataGridView1.Rows[rowIndex].Cells["Column4"].Value = data.Unit;
                }
                AppendThresholdInfo($"成功从表 {tableName} 加载 {dataGridView1.Rows.Count} 行数据");
            }
            catch (Exception ex)
            {
                AppendThresholdInfo($"从数据库加载数据失败: {ex.Message}");
                MessageBox.Show($"从数据库加载数据失败: {ex.Message}", "错误",
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void button7_Click(object sender, EventArgs e)
        {
            if (comboBox103.SelectedItem == null)
            {
                MessageBox.Show("请先选择要删除的方案！", "提示",
                               MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            string schemeName = comboBox103.SelectedItem.ToString();
            DialogResult result = MessageBox.Show($"确定要删除方案 '{schemeName}' 吗？此操作不可恢复！",
                                                "确认删除",
                                                MessageBoxButtons.YesNo,
                                                MessageBoxIcon.Warning);
            if (result != DialogResult.Yes) return;
            try
            {
                _thresholdScheme.DeleteTable(schemeName);
                AppendThresholdInfo($"表 {schemeName} 删除成功");
                comboBox103.Items.Remove(schemeName);
                dataGridView1.Rows.Clear();
                if (comboBox103.Items.Count > 0)
                {
                    comboBox103.SelectedIndex = 0;
                }
                MessageBox.Show($"方案 '{schemeName}' 已成功删除", "成功",
                               MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                AppendThresholdInfo($"删除表 {schemeName} 失败: {ex.Message}");
                MessageBox.Show($"删除方案失败: {ex.Message}", "错误",
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void button8_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            
        }
    }
}

